<template>
    <div ref="mapRef" class="map-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"
import { loadAMap } from "@/utils/useAMap"
import { qingyunMapData } from "@/utils/qingyun"
import type AMap from '@amap/amap-jsapi-types'
const mapRef = ref<HTMLDivElement | null>(null)

onMounted(async () => {
    try {
        const AMap = await loadAMap("SGLBZ-VUZ63-A4I3L-OF6HW-YQXNZ-SPFEI")

        if (!AMap) {
            console.error('AMap 加载失败')
            return
        }

        if (!mapRef.value) return

        const map = new AMap.Map(mapRef.value, {
            zoom: 11,
            center: [117.385, 37.777], // 庆云县大致中心点
        })

        // 1. 加载庆云县边界
        AMap.plugin("AMap.DistrictSearch", () => {
            const district = new AMap.DistrictSearch({
                level: "district",
                extensions: "all",
            })

            district.search("庆云县", (status, result) => {
                const bounds = result.districtList[0].boundaries
                if (!bounds) return

                // 绘制庆云县 polygon
                const polygon = new AMap.Polygon({
                    path: bounds,
                    strokeColor: "#00aaff",
                    strokeWeight: 2,
                    fillColor: "rgba(0,170,255,0.2)",
                })

                polygon.setMap(map)
                map.setFitView([polygon])

                // 点击庆云县 → 展示下级镇街
                polygon.on("click", () => {
                    showTownship(map, AMap)
                })
            })
        })

        function showTownship(map: AMap.Map, AMap: typeof window.AMap) {
            // 清除原有覆盖物
            map.clearMap()

            qingyunMapData.features.forEach((f) => {
                const coords = f.geometry.coordinates[0].map((c) => [c[0], c[1]])

                const poly = new AMap.Polygon({
                    path: coords,
                    strokeColor: "#ff6600",
                    strokeWeight: 2,
                    fillColor: "rgba(255,102,0,0.3)",
                })

                poly.setMap(map)

                poly.on("click", () => {
                    alert("点击了 " + f.properties.name)
                })
            })

            map.setFitView()
        }
    } catch (error) {
        console.error('AMap 初始化失败:', error)
    }
})
</script>

<style scoped>
.map-container {
    width: 100%;
    height: 100%;
}
</style>
